<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    /* 1）全局中的this
    ​	指向window对象 */
    var x = 100;
    console.log(this); //指向window
    console.log(window.x, this.x, x);
    console.log(window === this); //true
    /* 2）函数中的this
    ​	原则：谁调用就指向谁。一般情况下是指向window对象的。
    ​	如果开启了“use strict;”严格代码格式，this指向window。 */
    var name = "tom";
    function fn() {
      var name = "mickle";
      console.log(this.name); //tom
      console.log(name); //mickle
    }
    fn();

    ("use strict"); //严格代码模式
    var name = "tom";
    function fn() {
      var name = "mickle";
      console.log(this.name); //严格代码模式下，this指向window
      console.log(this);
    }
    fn();
    /* 3）对象方法中的this
    指向当前对象。 */
    var obj = {
      id: "0001",
      goodsName: "dell笔记本电脑",
      price: 6888,
      salePrice: function () {
        console.log(this.goodsName + "的价格为" + this.price + obj.id);
        // console.log(id); id未定义
        console.log(this); //this指向当前对象
      },
    };
    obj.salePrice();

    /* 4）构造函数中的this
    ​	指向当前实例化的对象。 */
    function Car(name, type, color) {
      this.name = name;
      this.type = type;
      this.color = color;

      this.show = function () {
        console.log(this.name + this.type + this.color);
        console.log(this);
      };
    }
    Car.prototype.price = 199999;
    Car.prototype.run = function (time) {
      console.log(this.name + "百公里加速时间为" + time);
      console.log(this);
    };
    var car1 = new Car("大众", "SUV", "白色");
    var car2 = new Car("卡宴", "至尊版", "土豪金");
    car1.show();
    car1.run(100);
    car2.show();
    car2.run(50);
  </script>
</html>
